﻿using System.IO;
using TripleA.Core.Database;
using TripleA.Core.Database.SqlServer;
using TripleA.Core.Extensions.Database;
using TripleA.Core.Interfaces.Entities;
using TripleA.StoryQ;

namespace TripleA.Tests.Database
{
    public class DatabaseDomain : StoryQTestDomain<Context>
    {
        public const string DefaultValidSqlCmd = "select count(*) from [model].[sys].[databases]";
        public const string DefaultSqlCmdPath = @"C:\Program Files\Microsoft SQL Server\110\Tools\Binn\sqlcmd.exe";

        private string _scriptFilename;
        private string _sqlcmdExePath;
        private ISqlStatement _sqlQuery;
        private string _connectionName;

        public void TheConnectionNameIs_(string path)
        {
            _connectionName = path;
        }

        public void TheDefaultConnectionAppSettingIsUsed()
        {
            _connectionName = null;
        }

        public void TheSqlCommandIs_(string cmd)
        {
            _sqlQuery = SqlServerStatement.Create(cmd);
        }

        public void TheDefaultValidSqlCommandIsUsed()
        {
            TheSqlCommandIs_(DefaultValidSqlCmd);
        }

        public void TheRunQueryStepIsCalled()
        {
            SafeExecute(() =>
                            {
                                if (string.IsNullOrWhiteSpace(_connectionName))
                                    TripleA.RunSqlQuery(_sqlQuery, rows => rows > 0);
                                else
                                    TripleA.RunSqlQuery(_connectionName, _sqlQuery, rows => rows > 0);
                            });
        }


        public void TheSqlCmdExeLocationIs_(string path)
        {
            _sqlcmdExePath = path;
        }

        public void TheDefaultSqlCmdExeLocationIsUsed()
        {
            TheSqlCmdExeLocationIs_(DefaultSqlCmdPath); 
        }

        public void TheSqlCmdLocationIsDefinedInTheAppSettings()
        {
            _sqlcmdExePath = null;
        }

        public void TheSqlScriptIs_(string script)
        {
            _scriptFilename = script;
        }

        public void TheRunScriptStepIsCalled()
        {
            SafeExecute(() =>
                            {
                                if (string.IsNullOrWhiteSpace(_sqlcmdExePath))
                                    TripleA.RunSqlScript(".", Path.Combine(@"Database\TestData", _scriptFilename));
                                else
                                    TripleA.RunSqlScriptExplicitSqlCmdPath(".",
                                        Path.Combine(@"Database\TestData", _scriptFilename), _sqlcmdExePath);
                            });
        }
    }
}